#pragma once

#include "qthreadproducer.h"
#include "qthreadconsumer.h"
#include <QMutex>
#include <QWaitCondition>
#include <queue>

QWaitCondition g_waitCond;
QMutex g_mutex;
std::queue<int> g_PCQueue;

// producer
QThreadProducer::QThreadProducer(QObject* parent) {

}

QThreadProducer::~QThreadProducer() {

}

void QThreadProducer::stop()
{
	m_stop = true;
}

void QThreadProducer::run() {
	m_stop = false;
	while (!m_stop) {
		srand(QTime::currentTime().msec());
		int diceValue = rand() % 6 + 1;
		g_mutex.lock();
		/*int diceValue = test;
		++test;*/
		g_PCQueue.emplace(diceValue);
		g_mutex.unlock();
		g_waitCond.notify_all();
		msleep(500);
	}
	g_waitCond.notify_all();
	this->quit();
}

// consumer
QThreadConsumer::QThreadConsumer(QObject* parent) {

}

QThreadConsumer::~QThreadConsumer() {

}

void QThreadConsumer::run()
{
	m_stop = false;
	while (!m_stop) {
		g_mutex.lock();
		while (g_PCQueue.empty() && !m_stop) {
			g_waitCond.wait(&g_mutex);
		}
		if (m_stop) { 
			g_mutex.unlock();
			break; 
		}
		assert(!g_PCQueue.empty());
		int diceValue = g_PCQueue.front();
		g_PCQueue.pop();
		emit newValue(diceValue);
		g_mutex.unlock();
	}
	this->quit();
}

void QThreadConsumer::stop()
{
	m_stop = true;
}
